package pannel.category;

import javax.swing.*;
import java.awt.*;

public class CategoryDialog extends JDialog {
    private JTextField nameField;
    private JTextArea descriptionArea;
    private boolean confirmed = false;
    private Category category;

    public CategoryDialog(Frame owner, String title, Category category) {
        super(owner, title, true);
        this.category = category;
        setupDialog();
    }

    private void setupDialog() {
        setLayout(new BorderLayout());
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 分类名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(new JLabel("分类名称:"), gbc);
        nameField = new JTextField(20);
        gbc.gridx = 1;
        mainPanel.add(nameField, gbc);

        // 分类描述
        gbc.gridx = 0;
        gbc.gridy = 1;
        mainPanel.add(new JLabel("分类描述:"), gbc);
        descriptionArea = new JTextArea(3, 20);
        descriptionArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(descriptionArea);
        gbc.gridx = 1;
        mainPanel.add(scrollPane, gbc);

        // 填充现有数据
        if (category != null) {
            nameField.setText(category.getName());
            descriptionArea.setText(category.getDescription());
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(getOwner());
        setResizable(false);
    }

    private boolean validateInput() {
        String name = nameField.getText().trim();

        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "分类名称不能为空");
            return false;
        }

        return true;
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getCategoryName() {
        return nameField.getText().trim();
    }

    public String getDescription() {
        return descriptionArea.getText().trim();
    }
} 